<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="监测量名称">
          <el-input v-model="searchForm.name" placeholder="请输入监测量名称" clearable  style="width: 300px;"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 300px;">
            <el-option label="启用" :value="0" />
            <el-option label="停用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
        <el-icon>
          <Delete />
        </el-icon>
        批量删除
      </el-button>
      <el-table v-loading="loading" :data="tableData" border style="width: 100%"
        @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="name" label="监测量名称"  align="center"/>
        <el-table-column prop="formula" label="计算公式"  align="center"/>
        <el-table-column prop="frequency" label="更新频率(秒)" align="center">
          <template #default="{ row }">
            {{ row.frequency }}秒
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button size="small" type="primary" @click="handleCalculate(row)">
              <el-icon>
                <DataLine />
              </el-icon>
              计算
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :before-close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="监测量名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入监测量名称" />
        </el-form-item>
        <el-form-item label="计算公式" prop="formula">
          <el-input v-model="formData.formula" type="textarea" :rows="3" placeholder="请输入计算公式，如: A1 + B2 * 0.5" />
        </el-form-item>
        <el-form-item label="更新频率(秒)" prop="frequency">
          <el-input-number v-model="formData.frequency" :min="1" :max="3600" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="测点列表">
          <el-select v-model="formData.points" multiple placeholder="请选择测点" style="width: 100%">
            <el-option v-for="point in pointOptions" :key="point.id" :label="point.pointName"
              :value="point.pointName" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleTestFormula">测试公式</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 公式计算对话框 -->
    <el-dialog v-model="calculateDialogVisible" title="公式计算结果" width="60%">
      <el-form label-width="120px">
        <el-form-item label="计算公式">
          <el-input v-model="currentFormula" readonly />
        </el-form-item>
        <el-form-item label="参数设置">
          <div v-for="(param, index) in formulaParams" :key="index" class="param-item">
            <el-input v-model="param.key" placeholder="参数名" style="width: 150px" />
            <el-input-number v-model="param.value" placeholder="参数值" style="width: 200px; margin-left: 10px" />
            <el-button type="danger" :icon="Delete" circle style="margin-left: 10px" @click="removeParam(index)" />
          </div>
          <el-button type="primary" @click="addParam">
            <el-icon>
              <Plus />
            </el-icon>
            添加参数
          </el-button>
        </el-form-item>
        <el-form-item label="计算结果">
          <el-input v-model="calculateResult" readonly>
            <template #append>
              <el-button type="primary" @click="executeCalculate">计算</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="错误信息" v-if="calculateError">
          <el-alert :title="calculateError" type="error" show-icon />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="calculateDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  Edit,
  DataLine
} from '@element-plus/icons-vue'
import {
  getMeasurementsList,
  getMeasurementDetail,
  addMeasurement,
  updateMeasurement,
  deleteMeasurement,
  calculateFormula,
  getMonitoringPointList
} from '@/api/park/monitor/statistics'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const formData = reactive({
  id: '',
  name: '',
  formula: '',
  frequency: 60,
  status: 0,
  points: []
})

// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: '请输入监测量名称', trigger: 'blur' }],
  formula: [{ required: true, message: '请输入计算公式', trigger: 'blur' }],
  frequency: [{ required: true, message: '请输入更新频率', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

// 测点选项
const pointOptions = ref([])

// 公式计算相关
const calculateDialogVisible = ref(false)
const currentFormula = ref('')
const formulaParams = ref([{ key: '', value: 0 }])
const calculateResult = ref('')
const calculateError = ref('')

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.size
    }
    const res = await getMeasurementsList(params)
    tableData.value = res.rows
    pagination.total = res.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载测点列表
const loadPointOptions = async () => {
  try {
    const res = await getMonitoringPointList()
    pointOptions.value = res.data
  } catch (error) {
    console.error('加载测点列表失败:', error)
    ElMessage.error('加载测点列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增统计监测量'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  try {
    loading.value = true
    const res = await getMeasurementDetail(row.id)
    Object.assign(formData, res.data)
    dialogTitle.value = '编辑统计监测量'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除监测量 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMeasurement(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) return

  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMeasurement(selectedIds.value.join(','))
      ElMessage.success('删除成功')
      selectedIds.value = []
      loadData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.name = ''
  formData.formula = ''
  formData.frequency = 60
  formData.status = 0
  formData.points = []
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (formData.id) {
      await updateMeasurement(formData)
      ElMessage.success('更新成功')
    } else {
      await addMeasurement(formData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.message !== 'validate') {
      ElMessage.error('提交失败')
    }
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
}

// 测试公式
const handleTestFormula = () => {
  if (!formData.formula) {
    ElMessage.warning('请输入计算公式')
    return
  }

  currentFormula.value = formData.formula
  formulaParams.value = extractParams(formData.formula)
  calculateDialogVisible.value = true
}

// 提取公式中的参数
const extractParams = (formula) => {
  // 简单提取变量名，实际项目中可能需要更复杂的解析
  const regex = /[A-Za-z_]\w*/g
  const params = new Set()
  let match

  while ((match = regex.exec(formula)) !== null) {
    params.add(match[0])
  }

  return Array.from(params).map(key => ({ key, value: 0 }))
}

// 添加参数
const addParam = () => {
  formulaParams.value.push({ key: '', value: 0 })
}

// 移除参数
const removeParam = (index) => {
  formulaParams.value.splice(index, 1)
}

// 执行计算
const executeCalculate = async () => {
  try {
    const params = {}
    formulaParams.value.forEach(param => {
      if (param.key) {
        params[param.key] = param.value
      }
    })

    const res = await calculateFormula({
      formula: currentFormula.value,
      parameters: params
    })

    if (res.data.success) {
      calculateResult.value = res.data.result
      calculateError.value = ''
    } else {
      calculateResult.value = ''
      calculateError.value = res.data.error || '计算失败'
    }
  } catch (error) {
    console.error('计算失败:', error)
    calculateResult.value = ''
    calculateError.value = error.message || '计算失败'
  }
}

// 计算按钮点击
const handleCalculate = (row) => {
  currentFormula.value = row.formula
  formulaParams.value = extractParams(row.formula)
  calculateResult.value = ''
  calculateError.value = ''
  calculateDialogVisible.value = true
}

// 初始化
onMounted(() => {
  loadData()
  loadPointOptions()
})
</script>

<style scoped>


.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.operation-buttons {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.param-item {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 10px;
}

.empty-data {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>